<template>
    <div>
        <div>
            <div>
                <h1>主页</h1>
                <span v-show="user.username"> —— 欢迎回来 {{ user.username }}</span>
            </div>
            <div>
                <a href="javascript:" v-show="user.username" @click="logout()">退出登录</a>
                <router-link v-show="!user.username" :to="{ name: 'Login' }">立即登录</router-link>
            </div>
        </div>
        <hr />
        <div>
            <router-link :to="{ name: 'Users' }">员工管理</router-link>
        </div>
        <router-view></router-view>
    </div>
</template>

<script>
import instance from '../utils/request';

export default {
    name: "Index",
    data() {
        return {
            user: {} //用户信息
        }
    },
    methods: {
        logout() {
            instance.get("/user/logout?username=" + this.user.username + "").then(success => {
                if (success.data.code == 200) {
                    localStorage.removeItem("username");
                    localStorage.removeItem("token");
                    this.user = {};
                } else {
                    alert(success.data.msg);
                }
            }).catch(error => {
                console.log(error);
            });
        }
    },
    created() {
        let username = localStorage.getItem("username");
        if (username == null) {
            //用户还没有登录过
            return;
        } else {
            instance.get("/user/cur?username=" + username + "").then(success => {
                if (success.data.code == 200) {
                    this.user = success.data.data;
                } else {
                    alert("获取当前登录用户信息失败! 原因：" + success.data.msg);
                }
            }).catch(error => {
                console.log(error);
            })
        }

    }
};
</script>

<style scoped></style>